<template>
    <div class="container blog-detail">
        <div class="left">
            <div class="title">{{ blogInfo.title }}</div>
            <div class="info">
                <span class="time">编辑时间:{{ blogInfo.time }}</span>
                <span class="writer"> 作者:<router-link to="/" class="a-link"> {{ blogInfo.writer }}</router-link></span>
                <span class="categoryName">分类: <router-link to="/" class="a-link">{{
                    blogInfo.categoryName }}</router-link></span>
            </div>
            <div v-html="blogInfo.content" class="content"></div>
            <div class="comment">
                <div>
                    <el-input type="textarea" placeholder="请输入评论" rows="3" v-model="cm"></el-input>
                    <div style="text-align: right; margin: 10px 0;">
                        <el-button type="primary" @click="submit" style="">评论</el-button>
                    </div>
                </div>
                <div class="top">评论区</div>
                <div v-for="item in commentList" :key="item.id">
                    <Comment :id="item.id" :cover="item.cover" :content="item.content" :blogId="item.blogId"
                             :parentId="item.parentId"
                             :time="item.time" :username="item.username" :userId="item.userId"></Comment>
                </div>
            </div>
        </div>

        <div class="right">
            <div class="part-title">
                <span class="title">分类专栏</span>
                <router-link to="/" class="a-link">更多&gt;&gt;</router-link>
            </div>
            <div v-for="item in categoryList" :key="item.id">
                <CategoryItem :cover="item.cover" :name="item.categoryName" :blogCount="item.blogCount"
                              :categoryId="item.categoryId"></CategoryItem>
            </div>
        </div>
    </div>
</template>

<script setup>
    import {ref, onMounted} from 'vue';
    import {useRoute} from 'vue-router';
    import axios from 'axios';
    import Comment from '../../components/Comment.vue';

    const route = useRoute();
    const blogId = ref(route.params.blogId)
    const blogInfo = ref({})
    const blogData = ref({
        cover: "",
        categoryName: "",
        title: "",
        writer: "", // 确保writer的值被正确设置
        allowComment: "",
        status: "",
        content: "",
        description: "",
        categoryId: "",
        allowIssue: "",
        statusName: "",
        time: ""
    });
    const cm = ref('');
    const currentTime = new Date();
    const commentData = ref({
        blogId: "",
        userId: "",
        username: "",
        time: "",
        parentId: "",
        content: "",
        cover: "",
    })
    // 获取令牌信息
    const jwtToken = localStorage.getItem('jwtToken');
    if (jwtToken) {
        // 解码JWT令牌（假设它是一个包含用户名的 JSON）
        const tokenData = JSON.parse(decodeURIComponent(escape(atob(jwtToken.split('.')[1]))));
        commentData.username = tokenData.username;
        commentData.cover = tokenData.cover;
        commentData.userId = tokenData.id;
    }

    const axiosInstance = axios.create({
        headers: {
            'Token': jwtToken // 将JWT令牌放入请求头的token字段
        }
    });
    axiosInstance.get(`http://localhost:8080/showdata/${blogId.value}`)
        .then(response => {
            const responseData = response.data;
            blogInfo.value = responseData.data
        })
        .catch(error => {
            console.error('请求失败:', error);
        });


    axiosInstance.post('http://localhost:8080/es/addBlog',blogInfo)
        .then(response => {
           console.log(blogInfo.value);
        })
        .catch(error => {
            console.error('请求失败:', error);
        });

    //分类就是分类列表
    const categoryList = ref([]);
    const commentList = ref([]);
    const rightMarginLeft = ref(1040 + (window.innerWidth - 1350) / 2)
    axiosInstance.get('http://localhost:8080/show')
        .then(response => {
            const responseData = response.data;
            if (Array.isArray(responseData.data) && responseData.data.length > 0) {
                categoryList.value = responseData.data; // 赋值给tableData
            }
        })
        .catch(error => {
            console.error('请求失败:', error);

        });
    axiosInstance.get(`http://localhost:8080/showcomment/${blogId.value}`)
        .then(response => {
            const responseData = response.data;
            commentList.value = responseData.data
        })
        .catch(error => {
            console.error('请求失败:', error);
        });

    //评论
    const submit = () => {
        commentData.content = cm.value;
        commentData.blogId = blogId.value;
        const options = {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        };
        const formattedTime = currentTime.toLocaleString(undefined, options);
        commentData.time = formattedTime;
        axiosInstance.post('http://localhost:8080/insertComment', commentData)
            .then(response => {
                location.reload();
            })
            .catch(error => {
                console.error('请求失败:', error);
            });
    }
</script>

<style lang="scss">
    .blog-detail {
        display: flex;
        margin-top: 10px;

        .left {
            flex: 1;
            background: #fff;
            padding: 15px;

            .comment {
                padding-top: 10px;
            }
        }

        .right {
            margin-left: 10px;
            width: 300px;
            background: #fff;

            .part-title {
                display: flex;
                align-items: center;
                justify-content: space-between;
                border-bottom: 1px solid #ddd;
                padding: 0px 5px 8px 5px;
                text-decoration: none;
            }
        }

        .title {
            font-weight: bold;
            font-size: 25px;
        }

        .info {
            background: #f4f4f4;
            padding: 15px;
            font-size: 14px;
            margin-top: 10px;
            color: #546471;

            .categoryName {
                margin-right: 10px;
            }

            .writer {
                margin-right: 10px;
            }

            .time {
                margin-right: 10px;
                font-size: 13px
            }
        }

        .content {
            margin-top: 20px;
            line-height: 26px;
            word-break: break-all;

            img {
                width: 100%;
            }
        }
    }</style>